package edu.zut.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //获取用户的请求url,如果用户访问的不是登录相关请求，
        // 需要判断当前请求是否已完成登录，如果没登录，让用户先登录后访问
        //如果登录，直接放行
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getServletPath();
        System.out.println(!(uri.contains("/login") || uri.contains("/index")));
        if (!(uri.contains("/login") || uri.contains("/index"))) {
            HttpSession session = req.getSession();
            Object loginStatus = session.getAttribute("loginStatus");
            System.out.println("loginStatus = " + loginStatus);
            if (loginStatus == null || loginStatus.equals("")) {
                req.setAttribute("error", "请先登录后访问");
                req.getRequestDispatcher("/view/login.jsp").forward(req, resp);
            }
        }
        chain.doFilter(req, resp);

    }
}
